/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cjava.system.bean.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.cjava.system.bean.IndexUserBean;
import org.cjava.system.bean.NavigatorClientBean;
import org.cjava.system.model.BusinessAssociate;
import org.cjava.system.model.ConfigEmail;
import org.cjava.system.model.District;
import org.cjava.system.model.Meeting;
import org.cjava.system.model.MeetingBusinessAssociate;
import org.cjava.system.model.Person;
import org.cjava.system.model.PersonProfile;
import org.cjava.system.model.Profile;
import org.cjava.system.model.State;
import org.cjava.system.model.SystemUser;
import org.cjava.system.model.University;
import org.cjava.system.service.interfac.IBusinessAssociateService;
import org.cjava.system.service.interfac.IMeetingBusinessAssociateService;
import org.cjava.system.service.interfac.IMeetingService;
import org.cjava.system.service.interfac.IPersonProfileService;
import org.cjava.system.service.interfac.IPersonService;
import org.cjava.system.service.interfac.IProfileService;
import org.cjava.system.service.interfac.ISystemUserService;
import org.cjava.system.service.interfac.IUniversityService;
import org.cjava.system.util.Clazz;
import org.cjava.system.util.faces.FacesUtil;
import org.omnifaces.util.Faces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DualListModel;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author max
 */
@ManagedBean
@SessionScoped
public class ClientBean implements Serializable {

    private static final long serialVersionUID = 1L;
    // <editor-fold defaultstate="collapsed" desc="Servicios"> 
    @ManagedProperty("#{businessAssociateService}")
    IBusinessAssociateService businessAssociateService;
    @ManagedProperty("#{systemUserService}")
    ISystemUserService systemUserService;
    @ManagedProperty("#{universityService}")
    IUniversityService universityService;
    @ManagedProperty("#{personService}")
    IPersonService personService;
    @ManagedProperty("#{meetingService}")
    IMeetingService meetingService;
    @ManagedProperty("#{meetingBusinessAssociateService}")
    IMeetingBusinessAssociateService meetingBusinessAssociateService;
    @ManagedProperty("#{profileService}")
    IProfileService profileService;
    @ManagedProperty("#{personProfileService}")
    IPersonProfileService personProfileService;
    ///////////////////////BEAN'S///////////////////////////
    @ManagedProperty("#{navigatorClientBean}")
    NavigatorClientBean navigatorClientBean;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    // </editor-fold> 

    private BusinessAssociate businessAssociateLoged = new BusinessAssociate();
    private List<Meeting> listMeetings;
    private List<MeetingBusinessAssociate> listMeetingBusinessAssociates;
    private String oldPass;
    private String newPass;
    private String repetNewPass;
    /////////////////////BOLSA DE TRABAJO ////////////////////
    private DualListModel<Profile> listDataBases;
    private DualListModel<Profile> listLanguages;
    private DualListModel<Profile> listCertifications;
    private DualListModel<Profile> listTools;
    private DualListModel<Profile> listFrameworks;

    //
    /////////////////////////////////////////////////////////////
    public void initProfileForPerson() {
        listDataBases = null;
        listLanguages = null;
        listCertifications = null;
        listTools = null;
        listFrameworks = null;
    }

    public void handleFileUpload(FileUploadEvent event) throws IOException, Exception {
        String path = FacesContext.getCurrentInstance().getExternalContext()
                .getRealPath("/");
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String name = fmt.format(new Date())
                + event.getFile().getFileName().substring(
                        event.getFile().getFileName().lastIndexOf('.'));
        String fullPath = path + "resources/files/cv/" + name;
        fullPath = fullPath.replace("/", File.separatorChar + "");

        if (businessAssociateLoged.getIdPerson().getCurriculumUrl() != null
                && !businessAssociateLoged.getIdPerson().getCurriculumUrl().isEmpty()) {
            // YA EXISTE UN ARCHIVO POR LO QUE TENEMOS QUE BORRAR ESE ARCHIVO DEL SERVIDOR PARA 
            // QUE NO SE LLENE DE DATOS.
            String pathTemp = path + "resources/files/cv/" + businessAssociateLoged.getIdPerson().getCurriculumUrl();
            pathTemp = pathTemp.replace("/", File.separatorChar + "");
            File fileOld = new File(pathTemp);
            if (fileOld.exists()) {
                fileOld.delete();
            }
        }

        File file = new File(fullPath);

        InputStream is = event.getFile().getInputstream();
        OutputStream out = new FileOutputStream(file);
        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        is.close();
        out.close();

        businessAssociateLoged.getIdPerson().setCurriculumUrl(name);
        personService.HQLexecute("update Person p set p.curriculumUrl='" + name + "' "
                + "where p.id=" + businessAssociateLoged.getIdPerson().getId());

        FacesUtil.addMessage("Su CV se encuentra con nosotros en estos momentos.", null, FacesMessage.SEVERITY_INFO);
    }

    public void saveOrUpdateProfile() throws Exception {
        List<PersonProfile> listTemp = new ArrayList<>();
        for (Profile pro : listDataBases.getTarget()) {
            listTemp.add(new PersonProfile(pro, businessAssociateLoged.getIdPerson()));
        }
        for (Profile pro : listLanguages.getTarget()) {
            listTemp.add(new PersonProfile(pro, businessAssociateLoged.getIdPerson()));
        }
        for (Profile pro : listCertifications.getTarget()) {
            listTemp.add(new PersonProfile(pro, businessAssociateLoged.getIdPerson()));
        }
        for (Profile pro : listTools.getTarget()) {
            listTemp.add(new PersonProfile(pro, businessAssociateLoged.getIdPerson()));
        }
        for (Profile pro : listFrameworks.getTarget()) {
            listTemp.add(new PersonProfile(pro, businessAssociateLoged.getIdPerson()));
        }
        System.out.println("TotalEn contenedor: " + businessAssociateLoged.getIdPerson().getPersonProfileList());
        for (PersonProfile per : businessAssociateLoged
                .getIdPerson()
                .getPersonProfileList()) {
            personProfileService.delete(per);
        }

        businessAssociateLoged.getIdPerson().setPersonProfileList(listTemp);
        personService.saveOrUpdate(businessAssociateLoged.getIdPerson());
        FacesUtil.addMessage("Información Guardada...", null, FacesMessage.SEVERITY_INFO);
        initProfileForPerson();
    }

    public StreamedContent getFileDowload() {
        String fullPath = "/resources/files/cv/" + businessAssociateLoged.getIdPerson().getCurriculumUrl();
        fullPath = fullPath.replace("/", File.separatorChar + "");
        InputStream stream = Faces.getResourceAsStream(fullPath);
        StreamedContent file = new DefaultStreamedContent(stream, "application/pdf", "cv-" + businessAssociateLoged.getIdPerson().getCompleteName() + ".pdf");
        return file;
    }

    public void handleFileUploadPhoto(FileUploadEvent event) throws IOException, Exception {
        String path = FacesContext.getCurrentInstance().getExternalContext()
                .getRealPath("/");

        if (businessAssociateLoged.getIdPerson().getPhoto() != null
                && !businessAssociateLoged.getIdPerson().getPhoto().isEmpty()) {
            // YA EXISTE UN ARCHIVO POR LO QUE TENEMOS QUE BORRAR ESE ARCHIVO DEL SERVIDOR PARA 
            // QUE NO SE LLENE DE DATOS.
            String pathTemp = path + "resources/files/photo/" + businessAssociateLoged.getIdPerson().getPhoto();
            pathTemp = pathTemp.replace("/", File.separatorChar + "");
            File fileOld = new File(pathTemp);
            if (fileOld.exists()) {
                fileOld.delete();
            }
        }
        //TRANSFORMAR EL NOMBRE CON EL ID DE LA PERSONA Y EL FORMATO
        // EJM: 152.png | 12.jpeg
        String name = businessAssociateLoged.getIdPerson().getId()
                + event.getFile().getFileName().substring(
                        event.getFile().getFileName().lastIndexOf('.'));

        String fullPath = path + "resources/files/photo/" + name;
        fullPath = fullPath.replace("/", File.separatorChar + "");
        File file = new File(fullPath);

        InputStream is = event.getFile().getInputstream();
        OutputStream out = new FileOutputStream(file);
        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        is.close();
        out.close();
        businessAssociateLoged.getIdPerson().setPhoto(name);
        personService.HQLexecute("update Person p set p.photo='" + name + "' "
                + "where p.id=" + businessAssociateLoged.getIdPerson().getId());

        FacesUtil.addMessage("Imagen Subida...", null, FacesMessage.SEVERITY_INFO);

    }

    public DualListModel<Profile> getListDataBases() throws Exception {
        if (listDataBases == null) {
            String hql = "from Profile p "
                    + "where p.type='(type)' order by p.name";
            hql = hql.replace("(type)", Clazz._TYPE_PROFILE._DATABASE);
            List listProfileSrc = profileService.listHQL(hql);
            listDataBases = new DualListModel<>(listProfileSrc, new ArrayList<Profile>());
            for (int i = 0; i < businessAssociateLoged
                    .getIdPerson()
                    .getPersonProfileList().size(); i++) {
                if (listDataBases.getSource()
                        .remove(businessAssociateLoged
                                .getIdPerson()
                                .getPersonProfileList()
                                .get(i).getIdProfile())) {
                    listDataBases.getTarget()
                            .add(businessAssociateLoged
                                    .getIdPerson()
                                    .getPersonProfileList()
                                    .get(i).getIdProfile());
                }
            }
        }
        return listDataBases;
    }

    public DualListModel<Profile> getListLanguages() throws Exception {
        if (listLanguages == null) {
            String hql = "from Profile p "
                    + "where p.type='(type)' order by p.name";
            hql = hql.replace("(type)", Clazz._TYPE_PROFILE._LANGUAGE);
            List listProfileSrc = profileService.listHQL(hql);
            listLanguages = new DualListModel<>(listProfileSrc,
                    new ArrayList<Profile>());
            for (int i = 0; i < businessAssociateLoged
                    .getIdPerson()
                    .getPersonProfileList().size(); i++) {
                if (listLanguages.getSource()
                        .remove(businessAssociateLoged
                                .getIdPerson()
                                .getPersonProfileList()
                                .get(i).getIdProfile())) {
                    listLanguages.getTarget()
                            .add(businessAssociateLoged
                                    .getIdPerson()
                                    .getPersonProfileList()
                                    .get(i).getIdProfile());
                }
            }
        }
        return listLanguages;
    }

    public DualListModel<Profile> getListCertifications() throws Exception {
        if (listCertifications == null) {
            String hql = "from Profile p "
                    + "where p.type='(type)' order by p.name";
            hql = hql.replace("(type)", Clazz._TYPE_PROFILE._CERTIFICATION);
            List listProfileSrc = profileService.listHQL(hql);
            listCertifications = new DualListModel<>(listProfileSrc, new ArrayList<Profile>());
            for (int i = 0; i < businessAssociateLoged
                    .getIdPerson()
                    .getPersonProfileList().size(); i++) {
                if (listCertifications.getSource()
                        .remove(businessAssociateLoged
                                .getIdPerson()
                                .getPersonProfileList()
                                .get(i).getIdProfile())) {
                    listCertifications.getTarget()
                            .add(businessAssociateLoged
                                    .getIdPerson()
                                    .getPersonProfileList()
                                    .get(i).getIdProfile());
                }
            }
        }
        return listCertifications;
    }

    public DualListModel<Profile> getListTools() throws Exception {
        if (listTools == null) {
            String hql = "from Profile p "
                    + "where p.type='(type)' order by p.name";
            hql = hql.replace("(type)", Clazz._TYPE_PROFILE._TOOLS);
            List listProfileSrc = profileService.listHQL(hql);
            listTools = new DualListModel<>(listProfileSrc, new ArrayList<Profile>());
            for (int i = 0; i < businessAssociateLoged
                    .getIdPerson()
                    .getPersonProfileList().size(); i++) {
                if (listTools.getSource()
                        .remove(businessAssociateLoged
                                .getIdPerson()
                                .getPersonProfileList()
                                .get(i).getIdProfile())) {
                    listTools.getTarget()
                            .add(businessAssociateLoged
                                    .getIdPerson()
                                    .getPersonProfileList()
                                    .get(i).getIdProfile());
                }
            }
        }
        return listTools;
    }

    public DualListModel<Profile> getListFrameworks() throws Exception {
        if (listFrameworks == null) {
            String hql = "from Profile p "
                    + "where p.type='(type)' order by p.name";
            hql = hql.replace("(type)", Clazz._TYPE_PROFILE._FRAMEWORK_JAVA);
            List listProfileSrc = profileService.listHQL(hql);
            listFrameworks = new DualListModel<>(listProfileSrc, new ArrayList<Profile>());
            for (int i = 0; i < businessAssociateLoged.getIdPerson()
                    .getPersonProfileList().size(); i++) {
                if (listFrameworks.getSource()
                        .remove(businessAssociateLoged
                                .getIdPerson()
                                .getPersonProfileList()
                                .get(i).getIdProfile())) {
                    listFrameworks.getTarget()
                            .add(businessAssociateLoged
                                    .getIdPerson()
                                    .getPersonProfileList()
                                    .get(i).getIdProfile());
                }
            }
        }
        return listFrameworks;
    }

    public void setListDataBases(DualListModel<Profile> listDataBases) {
        this.listDataBases = listDataBases;
    }

    public void setListLanguages(DualListModel<Profile> listLanguages) {
        this.listLanguages = listLanguages;
    }

    public void setListCertifications(DualListModel<Profile> listCertifications) {
        this.listCertifications = listCertifications;
    }

    public void setProfileService(IProfileService profileService) {
        this.profileService = profileService;
    }

    public void setPersonProfileService(IPersonProfileService personProfileService) {
        this.personProfileService = personProfileService;
    }

    public void setListTools(DualListModel<Profile> listTools) {
        this.listTools = listTools;
    }

    public void setListFrameworks(DualListModel<Profile> listFrameworks) {
        this.listFrameworks = listFrameworks;
    }

    //////////////////////////////////////////////////////////////
    // <editor-fold defaultstate="collapsed" desc="OTROS METODOS"> 
    public void initResetPassword() {
        listUniversity = null;
        person = new Person();
        idDistrict = null;
        businessAssociate = new BusinessAssociate();
    }

    public void initMeetingValues() {
        listMeetings = null;
        listMeetingBusinessAssociates = null;
    }

    /**
     * Pre-asistencia al curso que se muestra en la vista.
     *
     * @param idMeeting
     * @throws Exception
     */
    public void preAssistanceAvent(Meeting idMeeting) throws Exception {
        String hql = "from MeetingBusinessAssociate m "
                + "where m.idBusinessAssociate.id=" + businessAssociateLoged.getId()
                + " and m.idMeeting.id=" + idMeeting.getId();
        List<MeetingBusinessAssociate> meetingBusinessAssociates = meetingBusinessAssociateService.listHQL(hql);
        if (meetingBusinessAssociates.isEmpty()) {
            FacesUtil.addMessage("Lo esperamos en el evento", null, FacesMessage.SEVERITY_INFO);
            MeetingBusinessAssociate metTemp = new MeetingBusinessAssociate();
            metTemp.setComingIn(Calendar.getInstance().getTime());
            metTemp.setIdBusinessAssociate(businessAssociateLoged);
            metTemp.setIdMeeting(idMeeting);
            metTemp.setAssistance(false);

            meetingBusinessAssociateService.save(metTemp);
            initMeetingValues();
        } else {
            FacesUtil.addMessage("No puede volver a inscribirse", null, FacesMessage.SEVERITY_WARN);
        }

    }

    public List<Meeting> getListMeetings() throws Exception {
        if (listMeetings == null) {
            State st = clazz.STATE(Clazz._STATE._NAME._MEETING_FINALIZAR_EVENTO, Clazz._STATE._ENTITY._Meeting);
            
            if (!getListMeetingBusinessAssociates().isEmpty()) {
               String hql = "from Meeting m where "
                    + "m.idState.id!=" + st.getId()
                    + " and m.id not in (:list)";
                listMeetings = meetingService.listHQL(hql, 1, listMeetingBusinessAssociates);
            } else {
                String hql = "from Meeting m where "
                    + "m.idState.id!=" + st.getId();
                listMeetings = meetingService.listHQL(hql);
                
            }
            for (Meeting meeting : listMeetings) {
                    System.out.println("Meet: " + meeting);
                }
        }
        return listMeetings;
    }

    public void logOutAssociate() {
        try {
            Faces.removeSessionAttribute(FacesUtil.ATTREBUTE_USER_ASSOCIATE);
            Faces.logout();
            Faces.invalidateSession();
            Faces.redirect("sociedad.jsf");
        } catch (ServletException ex) {
            Logger.getLogger(IndexUserBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(IndexUserBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void savePerfil() throws Exception {
        businessAssociateLoged
                .getIdSystemUser()
                .setUserName(businessAssociateLoged.getIdPerson().getEmail());
        systemUserService.update(businessAssociateLoged
                .getIdSystemUser());
        personService.update(businessAssociateLoged.getIdPerson());
        businessAssociateService.update(businessAssociateLoged);
        FacesUtil.addMessage("Actualizo corractamente sus datos...", null, FacesMessage.SEVERITY_INFO);
    }

    public void changePassword() throws Exception {
        if (oldPass.trim().equals(businessAssociateLoged.getIdSystemUser().getPassword())) {
            if (newPass.equals(repetNewPass)) {
                businessAssociateLoged.getIdSystemUser().setPassword(newPass);
                systemUserService.update(businessAssociateLoged.getIdSystemUser());
                FacesUtil.addMessage("Su contraseña fué cambiada con éxito", null, FacesMessage.SEVERITY_INFO);
            } else {
                FacesUtil.addMessage("Contraseñas no coinciden...", null, FacesMessage.SEVERITY_WARN);
            }
        } else {
            FacesUtil.addMessage("Su contraseña no coincide con la antigua", null, FacesMessage.SEVERITY_ERROR);
        }
    }

    public List<MeetingBusinessAssociate> getListMeetingBusinessAssociates() throws Exception {
        if (listMeetingBusinessAssociates == null) {
            String hql = "from MeetingBusinessAssociate m "
                    + "where m.idBusinessAssociate.id=" + businessAssociateLoged.getId()
                    + " order by m.comingIn desc";
            System.out.println("Entrando a vert la lista de registrados...");
            listMeetingBusinessAssociates
                    = meetingBusinessAssociateService.listHQL(hql);

            for (int i = 0; i < listMeetingBusinessAssociates.size(); i++) {
                System.out.println(listMeetingBusinessAssociates.get(i));
            }
        }
        return listMeetingBusinessAssociates;
    }
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    public BusinessAssociate getBusinessAssociateLoged() {
        return businessAssociateLoged;
    }

    public void setListMeetingBusinessAssociates(List<MeetingBusinessAssociate> listMeetingBusinessAssociates) {
        this.listMeetingBusinessAssociates = listMeetingBusinessAssociates;
    }

    public void setListMeetings(List<Meeting> listMeetings) {
        this.listMeetings = listMeetings;
    }

    public String getOldPass() {
        return oldPass;
    }

    public void setOldPass(String oldPass) {
        this.oldPass = oldPass;
    }

    public void setMeetingService(IMeetingService meetingService) {
        this.meetingService = meetingService;
    }

    public String getNewPass() {
        return newPass;
    }

    public void setMeetingBusinessAssociateService(IMeetingBusinessAssociateService meetingBusinessAssociateService) {
        this.meetingBusinessAssociateService = meetingBusinessAssociateService;
    }

    public void setNewPass(String newPass) {
        this.newPass = newPass;
    }

    public String getRepetNewPass() {
        return repetNewPass;
    }

    public void setRepetNewPass(String repetNewPass) {
        this.repetNewPass = repetNewPass;
    }

    public void setBusinessAssociateLoged(BusinessAssociate businessAssociateLoged) {
        this.businessAssociateLoged = businessAssociateLoged;
    }

    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="todo lo que es el login del socio"> 
    // <editor-fold defaultstate="collapsed" desc="Fields utilizados no tocar"> 
    ////////////////FOR lOGGIN /////////////////
    private String userName;
    private String password;
    ////////////////END LOGGIN//////////////////
    private BusinessAssociate businessAssociate = new BusinessAssociate();
    private Person person = new Person();
    private Integer yearAssociate = Calendar.getInstance().get(Calendar.YEAR);
    /////////////////////////////////////////
    private List<University> listUniversity;
    private Integer idDistrict = null;
    ////////////////////////////////////////////////////////////////
    private ConfigEmail configEmail = new ConfigEmail();
    private String contentEmail;
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="loginClient"> 
    public void loginClient() throws IOException, Exception {
        System.out.println("Logeando");
        System.out.println(userName);
        System.out.println(password);

        String hql = "from BusinessAssociate b where "
                + "b.idSystemUser.userName='" + userName + "' "
                + "and b.idSystemUser.password='" + password + "' "
                + "and b.idSystemUser.type='" + Clazz._TYPE_SYSTEM_USER._SOCIO + "' "
                + "and b.idState.name='" + Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO + "'";
        System.out.println(hql);
        List<BusinessAssociate> listBus = businessAssociateService.listHQL(hql, 2, null);
        if (listBus.isEmpty()) {
            FacesUtil.addMessage("Usuario o password Incorrectos", null, FacesMessage.SEVERITY_ERROR);
        } else {
            businessAssociateLoged = listBus.get(0);
            Faces.setSessionAttribute(FacesUtil.ATTREBUTE_USER_ASSOCIATE, listBus.get(0));
            Faces.redirect("index_sociedad.jsf");
            FacesUtil.addMessage("Bienvenido Usuario", null, FacesMessage.SEVERITY_INFO);
        }

        //FacesUtil.addMessage("Pronto con muchos veneficios (No funcional)", null, FacesMessage.SEVERITY_INFO);
    }
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="savePreInscriptionAssociate"> 
    /**
     * GUARDAR UN PRE REGISTRO DE LA PÁGINA WEB DE SOCIEDAD
     */
    public void savePreInscriptionAssociate() {
        person.setStartDate(Calendar.getInstance().getTime());
        if (idDistrict != null) {
            person.setIdDistrict(new District(idDistrict));
        }

        try {
            String hql = "select p.id from Person p where p.dni='" + person.getDni() + "'";
            List<Integer> listId = personService.listHQL(hql);
            if (listId.isEmpty()) {
                // NO EXISTE PERSON, ASI QUE DEBE REGISTRARSE COMPLETO
                personService.save(person);
                navigatorClientBean.setNavigationContent("./pages/client/login.xhtml");
                FacesUtil.addMessage("Pre-Registro con éxito", null, FacesMessage.SEVERITY_INFO);
                initResetPassword();
                //MANDAR UN CORREO ELECTRONICO CON LOS DETALLES
            } else {
                //YA SE ENCUENTRA EN LA BASE DE DATOS
                FacesUtil.addMessage("Ya se encuentra Pre-Registrado...", null, FacesMessage.SEVERITY_WARN);
                initResetPassword();
            }

        } catch (Exception e) {
            FacesUtil.addMessage("Revise que los datos ingresados sean los correctos", null, FacesMessage.SEVERITY_ERROR);
        }

    }
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="Recovery Password"> 
    public void recoveryPassword() throws Exception {
        State state = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO,
                Clazz._STATE._ENTITY._BusinessAssociate);
        String hql = "from BusinessAssociate b "
                + "where b.idPerson.dni='" + person.getDni() + "' "
                + "and b.idPerson.email='" + person.getEmail() + "' "
                + "and b.idApertureAssociate.year=" + Calendar.getInstance().get(Calendar.YEAR) + " "
                + "and b.idState.id=" + state.getId();

        List<BusinessAssociate> listBus = businessAssociateService.listHQL(hql);
        if (listBus.isEmpty()) {
            // NO EXISTE UN SOCIO DE ESTE AÑO
            FacesUtil.addMessage("Ud. no es socio de este año :", null, FacesMessage.SEVERITY_WARN);
            //navigatorClientBean.setNavigationContent("./pages/client/register_person.xhtml");
        } else {
            // ES SOCIO Y SE LE DEBE MANDAR SU PASSWORD
            businessAssociate = listBus.get(0);
            String newPass = "Se recomienda cambiar su password... \n\n"
                    + " \n\nUsuario: "
                    + businessAssociate.getIdPerson().getEmail().trim() + "\n "
                    + "Password: cj@v@_" + businessAssociate.getIdPerson().getId() + businessAssociate.getId() + "\n\n";
            sendEmail(businessAssociate.getIdPerson().getEmail(), "Reestablecer Contraseña", newPass);
            personService.update(businessAssociate.getIdPerson());
            if (businessAssociate.getIdSystemUser() != null) {
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.MONTH, Calendar.DECEMBER);
                cal.set(Calendar.DATE, 31);
                businessAssociate.getIdSystemUser().setUserName(businessAssociate.getIdPerson().getEmail().trim());
                businessAssociate.getIdSystemUser().setPassword("cj@v@_" + businessAssociate.getIdPerson().getId() + businessAssociate.getId());
                businessAssociate.getIdSystemUser().setDescription("Socio realizo su petición de contraseña el dia :" + (new Date()));
                businessAssociate.getIdSystemUser().setType(Clazz._TYPE_SYSTEM_USER._SOCIO);
                businessAssociate.getIdSystemUser().setFinishDate(cal.getTime());
                systemUserService.update(businessAssociate.getIdSystemUser());
            } else {
                SystemUser sysTempPas = new SystemUser();
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.MONTH, Calendar.DECEMBER);
                cal.set(Calendar.DATE, 31);
                sysTempPas.setUserName(businessAssociate.getIdPerson().getEmail().trim());
                sysTempPas.setPassword("cj@v@_" + businessAssociate.getIdPerson().getId() + businessAssociate.getId());
                sysTempPas.setDescription("Socio realizo su petición de contraseña el dia :" + (new Date()));
                sysTempPas.setType(Clazz._TYPE_SYSTEM_USER._SOCIO);
                sysTempPas.setFinishDate(cal.getTime());
                sysTempPas.setId(systemUserService.save(sysTempPas));
                businessAssociate.setIdSystemUser(sysTempPas);
                businessAssociateService.update(businessAssociate);
            }
            //HACER EL PROCESO DE ENVIO DE CORREO
            initResetPassword();
            FacesUtil.addMessage("Puede revisar su correo electrónico", null, FacesMessage.SEVERITY_INFO);
        }
    }
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="sendEmail"> 
    public void sendEmail(String email, String title, String content) throws Exception {
        String HQL = "select max(c.id) from ConfigEmail c";
        List<Integer> ids = businessAssociateService.listHQL(HQL);
        if (ids.isEmpty()) {
            FacesUtil.addMessage("Temporalmente fuera de servicio...", null, FacesMessage.SEVERITY_INFO);
        } else {
            configEmail = (ConfigEmail) businessAssociateService.listHQL("from ConfigEmail c where c.id=" + ids.get(0)).get(0);
            contentEmail = "<div style=\"color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\">" + content + "<div dir=\"ltr\"><div><strong><div style=\"text-align: left;\"><span style=\"font-weight: normal;\"><strong><contenido><br>-----------------------------------------------------------------------------------------<br>SOCIOS CJAVA S&nbsp; |<br></contenido></strong></span></div></strong><div style=\"text-align: left;\">Oficina: Av. Arenales 395 oficina 403 &nbsp;</div></div><div><div style=\"text-align: left;\">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Cercado de Lima &nbsp;- Lima 01 - Perú</div><div style=\"text-align: left;\">Teléfonos: (511) 433-6948</div></div><div><div style=\"text-align: left;\">Web:<span class=\"Apple-converted-space\">&nbsp;</span><a href=\"http://www.cjavaperu.com/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\">http://www.cjavaperu.com</a></div><div style=\"text-align: left;\">Correo:<span class=\"Apple-converted-space\"> </span><a href=\"mailto:" + configEmail.getUserEmail() + "\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\">" + configEmail.getUserEmail() + "</a></div></div><div style=\"text-align: left;\"><br></div><div><font face=\"arial, sans-serif\"><b>Síguenos</b></font><b>&nbsp;en:</b>&nbsp;<a href=\"http://www.facebook.com/cjavaperu1\" target=\"_blank\" style=\"color: rgb(7, 77, 143);\"><img src=\"https://ci4.googleusercontent.com/proxy/dwlGZxzd_xuiJU14wDu04qxme65H6WoTTivARL3qpNw4P0Go4jDn3yaVB1-kJFKqwml1kyBqGf0D7KS517BfY5HvJA=s0-d-e1-ft#http://www.cjavaperu.com/uploads/facebook.png\"></a>&nbsp;<a href=\"http://twitter.com/@cjava_peru\" target=\"_blank\" style=\"color: rgb(7, 77, 143);\"><img src=\"https://ci4.googleusercontent.com/proxy/yg_fNFD26m8PswRUDjoi4dPQ6449XN6mNghybiDZOA7elmtXGsNiih5vPpemWYL9QATS_pa6sPpl2es1bCkMpyEd=s0-d-e1-ft#http://www.cjavaperu.com/uploads/twitter.png\"></a>&nbsp;<a href=\"https://plus.google.com/u/0/109384959685338323417\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/9GsvHDZ-XDcgZ0dEpg1OQ9fXGVAnC5ViRJSffU7yHcd3exAgoA6i9KfRQyzST7M8-6M4q8m68Ayo5DmLqA=s0-d-e1-ft#http://cjavaperu.com/logogoogleplus.png\"></a>&nbsp;<a href=\"http://pe.linkedin.com/pub/cjava-peru/43/524/726/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/0gNkW9GBU2GCn8U3bHcgQ3c54cVARnRYEmWWdM3b5y9cHsA3RliMwj1V8r_KRfg2He5rs2B4eFp2=s0-d-e1-ft#http://cjavaperu.com/logolinked.png\"></a>&nbsp;<a href=\"http://cjavaperu.com/blog/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/KaxgsYY44ngckVpqI6eegD-nvovU85zPzaWah1V3UPcC8K5xUD2lFbhda8MCQFiS_857HhvQlY35Jzbk=s0-d-e1-ft#http://cjavaperu.com/logowordpress.png\"></a></div><div><br></div><div><div style=\"text-align: justify;\"><p style=\"margin-bottom: 0.0001pt;\"><i><span style=\"font-family: Arial, sans-serif;\">La información contenida en este mensaje y sus posibles documentos adjuntos es privada y confidencial y está dirigida únicamente a su destinatario/a. Si usted no es el/la destinatario/a original de este mensaje, por favor elimínelo. La distribución o copia de este mensaje no está autorizada.</span></i></p><p style=\"margin-bottom: 0.0001pt; line-height: 13.4pt;\"><i><span style=\"font-family: Arial, sans-serif;\">Tardas 5 segundos en imprimir este e-mail, el árbol que servirá para hacer el papel, tardará 7 años en crecer. No imprimas este mensaje si no es necesario.</span></i></p></div></div></div></div><br class=\"Apple-interchange-newline\">";

            final String username = configEmail.getUserEmail();
            final String password = configEmail.getPasswordEmail();

            Properties props = new Properties();
            props.put("mail.smtp.socketFactory.port", configEmail.getPort());
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", configEmail.getPort());
            props.put("mail.smtp.host", configEmail.getHostName());

            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });

            try {

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(configEmail.getUserEmail()));
//            message.setRecipients(Message.RecipientType.TO,
//                    InternetAddress.parse("dcondor.cjavaperu@gmail.com"));
                //CORREOS SEPARADOS POR COMAS.
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(email, false));
                message.setSubject(title);

                message.setText(contentEmail, "utf-8", "html");

                Transport.send(message);
                //FacesUtil.addMessage("Revise su correo electrónico...", null, FacesMessage.SEVERITY_INFO);

            } catch (MessagingException e) {
                e.printStackTrace();
                FacesUtil.addMessage("Módulo desactivado por CJava", null, FacesMessage.SEVERITY_WARN);

            }

        }
    }
    // </editor-fold> 

    public void message() {
        System.out.println("Mensaje");
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    public void setNavigatorClientBean(NavigatorClientBean navigatorClientBean) {
        this.navigatorClientBean = navigatorClientBean;
    }

    public Integer getYearAssociate() {
        return yearAssociate;
    }

    public BusinessAssociate getBusinessAssociate() {
        return businessAssociate;
    }

    public void setBusinessAssociate(BusinessAssociate businessAssociate) {
        this.businessAssociate = businessAssociate;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setSystemUserService(ISystemUserService systemUserService) {
        this.systemUserService = systemUserService;
    }

    public Person getPerson() {
        return person;
    }

    public List<University> getListUniversity() throws Exception {
        if (listUniversity == null) {
            listUniversity = universityService.list();
        }
        return listUniversity;
    }

    public void setListUniversity(List<University> listUniversity) {
        this.listUniversity = listUniversity;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public Integer getIdDistrict() {
        return idDistrict;
    }

    public void setIdDistrict(Integer idDistrict) {
        this.idDistrict = idDistrict;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public void setBusinessAssociateService(IBusinessAssociateService businessAssociateService) {
        this.businessAssociateService = businessAssociateService;
    }

    public void setPersonService(IPersonService personService) {
        this.personService = personService;
    }

    public void setUniversityService(IUniversityService universityService) {
        this.universityService = universityService;
    }
    // </editor-fold> 
    // </editor-fold> 

}
